package com.platform.common.log.utils;

import com.platform.common.core.annotation.Excel;
import com.platform.common.core.utils.DateUtils;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.security.utils.SecurityUtils;
import io.swagger.annotations.ApiModelProperty;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Service;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

@Service
public class LogRecordUtils {


    /**
     * @rsDto: getNullPropertyNames
     * @name: 业务类型
     * @staFinal 操作类型:1.INSET 新增 2.DELETE 删除 3.UPDATA 修改
     */
    public static <T> String logRecord(T rsDto, String name, String staFinal) {
        String username = "null";
        HashMap<String, Object> map = new HashMap<>();
        String[] propertyNames = getNotNullPropertyNames(rsDto);
        try {
            map = testGetModelAop(rsDto, propertyNames);
            username = SecurityUtils.getLoginUser().getSysUser().getNickName();
        } catch (Exception e) {
            username = "admin";
        }
        StringBuffer logStr = new StringBuffer();
        int i = 0;
        for (String s : map.keySet()) {
            String str = i == (map.keySet().size() - 1) ? " " : ",";
            logStr = logStr.append(" " + s + " : " + map.get(s) + str + " ");
            i++;
        }
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return "【" + username + "】于【" + dateTime.format(formatter) + "】" + staFinal + "了" + name + ",内容为【" + logStr + "】";
    }

    /**
     * @Title: getNullPropertyNames
     * @Description: 获取值为空的属性名称
     * @createdBy:byrc
     */
    private static String[] getNotNullPropertyNames(Object source) {
        BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();


        Set<String> emptyNames = new HashSet<String>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue != null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    private static <T> HashMap<String, Object> testGetModelAop(T rsDto, String[] pds) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        Field[] fields = rsDto.getClass().getDeclaredFields();
        Field[] declaredFields = rsDto.getClass().getSuperclass().getDeclaredFields();
        for (Field f : fields) mapp(map, rsDto, f, pds);
        for (Field declaredField : declaredFields) mapp(map, rsDto, declaredField, pds);
        return map;
    }

    private static <T> HashMap<String, Object> mapp(HashMap<String, Object> map, T rsDto, Field f, String[] pds) throws Exception {
        for (String name : pds) {
            Excel anno = f.getAnnotation(Excel.class);
            if (anno != null) {
                if (name.equals(f.getName())) {
                    f.setAccessible(true);
                    String format="";
                    if (f.get(rsDto) instanceof Date)
                         format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(f.get(rsDto));
                    map.put(anno.name(),("".equals(format))?f.get(rsDto):format);
                }
            }
        }
        return map;
    }

}
